import singleton from "../libs/singleton"
import debounce from "../libs/debounce"

const CanIO = uni.requireNativePlugin('AThree-CanIO')

class Connect {
	#canId = 100
	#port = "can0"
	#band = 1000000
	#isConnect = false
	#interval
	#num = 0

	constructor() {
		//连接状态
		if (!this.#isConnect) this.#reconnect();
		this.#init()
	}



	#init() {
		console.log("SERIAL INIT SUCCESS!")
		CanIO.initCan("100", this.#port, this.#band, result => {
			//连接成功
			this.#isConnect = true;
			if (this.#interval) clearInterval(this.#interval)

			//监听硬件心跳 判断是否在线  不在在线重连设备
			// debounce(() => {
			// 	console.log('设备离线')
			// 	this.#isConnect = false;
			// 	this.#reconnect()
			// }, 5000)
			//数据分发
			this.watch(result)
		})

		//模拟接收数据

		// setInterval(_ => {
		// 	this.#num++
			
		// 	this.#isConnect = true;
		// 	if (this.#interval) clearInterval(this.#interval)
			
		// 	//监听硬件心跳 判断是否在线  不在在线重连设备
		// 	debounce(() => {
		// 		console.log('设备离线')
		// 		this.#isConnect = false;
		// 		this.#reconnect()
		// 	}, 5000)
		// 	this.watch(this.#num)
		// }, 3000)
	}

	#reconnect() {
		this.#interval = setInterval(() => {
			this.#init();
			console.log("重连中...")
		}, 5000)
	}

	send(canId, data) {
		CanIO.sendData(canId, data);
	}

	close() {
		CanIO.deInit()
	}

	watch(e) {

	}


}

export default singleton(Connect)